<?php	
	include dirname(__FILE__) . '/../common/Config.class.php';
	include dirname(__FILE__) . '/../common/DB.class.php';
	include dirname(__FILE__) . '/../common/pageInfo.class.php';
	$image_path = Config::getconfig("image_path");
	$server_path = Config::getconfig("server_path");

	class MainPic {

		var $id = "";
		var $navId = "";
		var $fileName = "";
		var $filePath = "";
		var $orderNum = "";
		var $state = "";

		function getId() {
			echo $this->id;
		}

		function setId($id) {
			$this->id = $id;
		}

		function getNavId() {
			echo $this->navId;
		}

		function setNavId($navId) {
			$this->navId = $navId;
		}

		function getFileName() {
			echo $this->fileName;
		}

		function setFileName($fileName) {
			$this->fileName = $fileName;
		}

		function getFilePath() {
			echo $this->filePath;
		}

		function setFilePath($filePath) {
			$this->filePath = $filePath;
		}

		function getOrderNum() {
			echo $this->orderNum;
		}

		function setOrderNum($orderNum) {
			$this->orderNum = $orderNum;
		}

		function getState() {
			echo $this->state;
		}

		function setState($state) {
			$this->state = $state;
		}

	}

	function getParamTypeStr($arr){
		$count = count($arr);
		$typestr = "";
		for($i = 0; $i<$count; $i++){
			$type = gettype($arr[$i]);
			switch($type){
				case "integer":
					$typestr.= "i";
					break;
				case "float":
				case "double":
					$typestr.= "d";
					break;
				case "string":
					$typestr.= "s";
					break;
			}
		}
		return $typestr;
	}


	function refValues($arr){
		if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
			$refs = array();
			foreach($arr as $key => $value)
				$refs[$key] = &$arr[$key];
			return $refs;
		}
		return $arr;
	}

	$result = array();
	$db = new DB();
	if(isset($_REQUEST['method']) && !empty($_REQUEST['method'])) {
		if ("list" === $_REQUEST['method']) {
			$pageInfo = new PageInfo();
			$arr = array();
			$args = array();
			$argsCount = array();

			$sql = "select id, nav_id, file_name, file_path, order_num, state from mz_main_pic";
			$sqlCount = "select count(*) from mz_main_pic";
			$sql .= " where 1=1 ";
			$sqlCount .= " where 1=1 ";
			if(isset($_REQUEST['name']) && !empty($_REQUEST['name'])) {
				$sql .= " and name like ? ";
				$sqlCount .= " and name like ? ";
				$args[] = "%".$_REQUEST['name']."%";
				$argsCount[] = "%".$_REQUEST['name']."%";
			}
			if(isset($_REQUEST['workId']) && !empty($_REQUEST['workId'])) {
				$sql .= " and work_id = ? ";
				$sqlCount .= " and work_id = ? ";
				$args[] = $_REQUEST['workId'];
				$argsCount[] = $_REQUEST['workId'];
			}
			$sql .= " order by order_num";
			$sql .= " limit ?, ?";
			$stmt = $db -> prepare($sql);

			/*
			$stmt->bind_param("ii", $start, $psize);
			// 设置参数并执行
			$start = $pageInfo->start;
			$psize = $pageInfo->pageSize;
			*/

			$callback = array($stmt, 'bind_param');
			// 将参数类型描述加入数组
			
			$args[] = $pageInfo->start;
			$args[] = $pageInfo->pageSize;

			array_unshift($args, getParamTypeStr($args)); 
			//call_user_func_array($callback, $args);

			call_user_func_array($callback, refValues($args));

			// 处理打算执行的SQL命令
			$stmt->execute();
			// 执行SQL语句
			$stmt->store_result();
			// 输出查询的记录个数
		    $stmt->bind_result($id, $nav_id, $file_name, $file_path, $order_num, $state);
		    $index = 0;
			while ($stmt->fetch())
		    {
		    	$work = new MainPic();
		    	$work->setId($id);
		    	$work->setNavId($nav_id);
		    	$work->setFileName($file_name);
		    	$work->setFilePath($file_path);
		    	$work->setOrderNum($order_num);
		    	$work->setState($state);
		    	$arr[$index] = $work;
		    	$index++;
		    } 

		    $stmt0 = $db -> prepare($sqlCount);

		    if(count($argsCount)>0) {
			    $callback0 = array($stmt0, 'bind_param');
				array_unshift($argsCount, getParamTypeStr($argsCount)); 
				//call_user_func_array($callback, $args);
				call_user_func_array($callback0, refValues($argsCount));
			}

			// 处理打算执行的SQL命令
			$stmt0->execute();
			// 执行SQL语句
			$stmt0->store_result();
			// 输出查询的记录个数
		    $stmt0->bind_result($count);
		    if ($stmt0->fetch())
		    {
		    	$pageInfo->setTotal($count);
		    } 

		    $pageInfo->setRows($arr);
		    
		    echo json_encode($pageInfo);

		} else if ("upload01" === $_REQUEST['method']) {
			// 允许上传的图片后缀
			$allowedExts = array("gif", "jpeg", "jpg", "png");
			$temp = explode(".", $_FILES["imgFile"]["name"]);
			$extension = end($temp);     // 获取文件后缀名
			if ((($_FILES["imgFile"]["type"] == "image/gif")
				|| ($_FILES["imgFile"]["type"] == "image/jpeg")
				|| ($_FILES["imgFile"]["type"] == "image/jpg")
				|| ($_FILES["imgFile"]["type"] == "image/pjpeg")
				|| ($_FILES["imgFile"]["type"] == "image/x-png")
				|| ($_FILES["imgFile"]["type"] == "image/png"))
				&& ($_FILES["imgFile"]["size"] < 20480000)   // 小于 200 kb
				&& in_array($extension, $allowedExts)) {
			    if ($_FILES["imgFile"]["error"] > 0) {
			        $result['error'] = $_FILES["imgFile"]["error"];
			    } else {
			        $result['filename'] = $_FILES["imgFile"]["name"];
			        $result['filetype'] = $_FILES["imgFile"]["type"];
			        $result['filesize'] = ($_FILES["imgFile"]["size"] / 1024) . "kB";
			        $result['filepath'] = $_FILES["imgFile"]["tmp_name"];
			        
			        // 判断当前目录下的 upload 目录是否存在该文件
			        // 如果没有 upload 目录，你需要创建它，upload 目录权限为 777
			        $imgPath = date("Ymd",time()); 
			        if (is_dir($image_path.$imgPath)) {

			        } else {
			        	mkdir($image_path.$imgPath, 0777, true);
			        }
			        if (file_exists($image_path.$imgPath."/".$_FILES["imgFile"]["name"])) {
			            $result['error'] =  $_FILES["imgFile"]["name"] . " 文件已经存在。 ";
			        } else {	        	
			            // 如果 upload 目录不存在该文件则将文件上传到 upload 目录下
			            $a =  $db->get_msectime();
			            $filename00 = $db->get_microtime_format($a*0.001);
			            move_uploaded_file($_FILES["imgFile"]["tmp_name"], $image_path.$imgPath."/".$filename00.".".$extension);
			            $result['msg'] =  "文件存储在: " . "/works/".$imgPath."/".$filename00.".".$extension;
			            $result['src'] = "/works/".$imgPath."/".$filename00.".".$extension;

			            $sql = "insert into mz_work_detail(id, work_id, file_name, file_path, order_num, state, main_flg) values(?,?,?,?,ifnull((select max(order_num) from mz_work_detail mwd where mwd.work_id=?)+1,1),?,?)";
						$stmt = $db -> prepare($sql);
						$stmt->bind_param("sssssss", $p01, $p02, $p03, $p04, $p05, $p06, $p07);
					 
						// 设置参数并执行
						$p01 = $db->uuid();
						$p02 = $_REQUEST['workId'];
						$p03 = $result['filename'];
						$p04 = $result['src'];
						$p05 = $_REQUEST['workId'];
						$p06 = "1";
						$p07 = "0";
						// 处理打算执行的SQL命令
						$stmt->execute();
			        }
			    }
			} else  {
			    $result['error'] =  "非法的文件格式";
			}
			$result['code'] = 0;
			$result['msg'] = "上传成功！！";
			echo json_encode($result);
		} else if ("upload02" === $_REQUEST['method']) {
			// 允许上传的图片后缀
			$allowedExts = array("gif", "jpeg", "jpg", "png");

			//$files = $_FILES['imgFile'];
			$files = array();
    		$i = 0;
    		//echo count($_FILES['imgFile']['name']) . "<br/>";
    		foreach ($_FILES as $file) {
    		//	echo $file['name'] . "<br/>";
        		if (is_string($file['name'])) {
		            $files[$i] = $file;
		            $i++;
        		} elseif (is_array($file['name'])) {
            		foreach ($file['name'] as $k => $v) {
		                $files[$i]['name'] = $file['name'][$k];
		                $files[$i]['type'] = $file['type'][$k];
		                $files[$i]['tmp_name'] = $file['tmp_name'][$k];
		                $files[$i]['error'] = $file['error'][$k];
		                $files[$i]['size'] = $file['size'][$k];
		                $i++;
		            }

		        }
		    }

		    for($k=0; $k<count($files); $k++) {
			    $temp = explode(".", $files[$k]["name"]);
				$extension = end($temp);     // 获取文件后缀名
				if ((($files[$k]["type"] == "image/gif")
					|| ($files[$k]["type"] == "image/jpeg")
					|| ($files[$k]["type"] == "image/jpg")
					|| ($files[$k]["type"] == "image/pjpeg")
					|| ($files[$k]["type"] == "image/x-png")
					|| ($files[$k]["type"] == "image/png"))
					&& ($files[$k]["size"] < 20480000)   // 小于 200 kb
					&& in_array($extension, $allowedExts)) {
				    if ($files[$k]["error"] > 0) {
				        $result['error'] = $files[$k]["error"];
				    } else {
				        $result['filename'] = $files[$k]["name"];
				        $result['filetype'] = $files[$k]["type"];
				        $result['filesize'] = ($files[$k]["size"] / 1024) . "kB";
				        $result['filepath'] = $files[$k]["tmp_name"];
				        
				        // 判断当前目录下的 upload 目录是否存在该文件
				        // 如果没有 upload 目录，你需要创建它，upload 目录权限为 777
				        $imgPath = date("Ymd",time()); 
				        if (is_dir($image_path.$imgPath)) {

				        } else {
				        	mkdir($image_path.$imgPath, 0777, true);
				        }
				        if (file_exists($image_path.$imgPath."/".$files[$k]["name"])) {
				            $result['error'] =  $files[$k]["name"] . " 文件已经存在。 ";
				        } else {	        	
				            // 如果 upload 目录不存在该文件则将文件上传到 upload 目录下
				            $a =  $db->get_msectime();
				            $filename00 = $db->get_microtime_format($a*0.001);
				            move_uploaded_file($files[$k]["tmp_name"], $image_path.$imgPath."/".$filename00.".".$extension);
				            $result['msg'] =  "文件存储在: " . "/works/".$imgPath."/".$filename00.".".$extension;
				            $result['src'] = "/works/".$imgPath."/".$filename00.".".$extension;

				            $sql = "insert into mz_work_detail(id, work_id, file_name, file_path, order_num, state, main_flg) values(?,?,?,?,ifnull((select max(order_num) from mz_work_detail mwd where mwd.work_id=?)+1,1),?,?)";
							$stmt = $db -> prepare($sql);
							$stmt->bind_param("sssssss", $p01, $p02, $p03, $p04, $p05, $p06, $p07);
						 
							// 设置参数并执行
							$p01 = $db->uuid();
							$p02 = $_REQUEST['workId'];
							$p03 = $result['filename'];
							$p04 = $result['src'];
							$p05 = $_REQUEST['workId'];
							$p06 = "1";
							$p07 = "0";
							// 处理打算执行的SQL命令
							$stmt->execute();
				        }
				    }
				} else  {
				    $result['error'] =  "非法的文件格式";
				}
			}
			$result['code'] = 0;
			$result['msg'] = "上传成功！！";
			echo json_encode($result);
		} else if ("save" === $_REQUEST['method']) {
			$arr = array();
			$args = array();
			$sql = "update mz_work_detail set id = ? ";
			$args[] = $_REQUEST['id'];
			if(isset($_REQUEST['state'])) {
				$sql .= " , state = ? ";
				$args[] = $_REQUEST['state'];
			}
			if(isset($_REQUEST['mainFlg'])) {
				$sql .= " , main_flg = ? ";
				$args[] = $_REQUEST['mainFlg'];

				$sql00 = "update mz_work_detail set main_flg='0' where work_id = ? ";
				$stmt00 = $db -> prepare($sql00);
				$stmt00->bind_param("s", $fworkId);
				// 设置参数并执行
				$fworkId = $_REQUEST['workId'];
				// 处理打算执行的SQL命令
				$stmt00->execute();

			}
			if(isset($_REQUEST['orderNum'])) {
				$sql .= " , order_num = ? ";
				$args[] = $_REQUEST['orderNum'];
			}
			$sql .= " where id = ? ";
			$stmt = $db -> prepare($sql);
			$callback = array($stmt, 'bind_param');
			// 将参数类型描述加入数组
			$args[] = $_REQUEST['id'];
			array_unshift($args, getParamTypeStr($args)); 
			//call_user_func_array($callback, $args);
			call_user_func_array($callback, refValues($args));
			// 处理打算执行的SQL命令
			$stmt->execute();
			$arr['code'] = 0;
			$arr['msg'] = "操作成功！！！";
		    echo json_encode($arr);
		} else if ("del" === $_REQUEST['method']) {
			$ids = $_POST['ids'];
			$str_arr = explode(",",$ids);

    		for($i=0; $i<count($str_arr); $i++){
				$sql = "delete from mz_work_detail where id = ?"; 
				$stmt = $db -> prepare($sql);
				$stmt->bind_param("s", $p1);
				// 设置参数并执行
				$p1 = $str_arr[$i];
				// 处理打算执行的SQL命令
				$stmt->execute();
			}

			$arr['code'] = 0;
			$arr['msg'] = "删除成功！！！";
			echo json_encode($arr);
		}
	}
?>